package com.example.lettcode.binarytreenode;

import java.util.ArrayDeque;
import java.util.Deque;

public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode() {}
    public TreeNode(int val) { this.val = val; }
    public TreeNode(int val, TreeNode left, TreeNode right) {
      this.val = val;
      this.left = left;
      this.right = right;
    }

      public TreeNode buildTreeNode(int[] nodes) {
          // 使用双端队列来存储节点，用于后续的左右子树构建
          Deque<TreeNode> stack = new ArrayDeque<>();
          TreeNode root = new TreeNode(nodes[0]);
          stack.push(root);

          int i = 1; // 用于遍历数组中的元素
          while (i < nodes.length) {
              TreeNode current = stack.peek(); // 获取当前节点

              // 左子节点
              if (i < nodes.length) {
                  current.left = new TreeNode(nodes[i]);
                  stack.push(current.left);
              }
              i++;

              // 右子节点
              if (i < nodes.length) {
                  current.right = new TreeNode(nodes[i]);
                  stack.push(current.right);
              }
              i++;

              // 移动到下一个父节点
              if (i == nodes.length) {
                  stack.pop(); // 完成当前节点的左右子节点构建，回到父节点
                  if (i < nodes.length) {
                      i++; // 跳过null值
                  }
              }
          }

          return root;
      }
  }